//
//  BaseViewController.swift
//  JXPagingView
//
//  Created by jiaxin on 2018/8/10.
//  Copyright © 2018年 jiaxin. All rights reserved.
//

import UIKit
import JXPagingView
import JXSegmentedView

extension JXPagingListContainerView: JXSegmentedViewListContainer {}

class BaseViewController: UIViewController {
    lazy var pagingView: JXPagingView = preferredPagingView()
    lazy var userHeaderView: XS_LearnHeaderView = preferredTableHeaderView()
    let dataSource: JXSegmentedTitleDataSource = JXSegmentedTitleDataSource()
    lazy var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 8, width: UIScreen.main.bounds.size.width, height: CGFloat(headerInSectionHeight)))
//    var titles = ["全部", "系列课", "免费好课","线下活动"]
    var titles = ["全部课程", "系列课程", "免费好课"]
    var tableHeaderViewHeight: Int = 369 + 96
    var headerInSectionHeight: Int = 44
    var isNeedHeader = false
    var isNeedFooter = false
    
    lazy var vcArray : [XS_MyCourseItemVC] = {
        var vcArray : [XS_MyCourseItemVC] = []
        for index in 0...titles.count{
            let list = XS_MyCourseItemVC()
            list.type = XS_MyCourseItemVCType(rawValue: index) ?? .all
            vcArray.append(list)
        }
        return vcArray
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationController?.navigationBar.isTranslucent = false

        dataSource.titles = titles
        dataSource.titleNormalColor = UIColor.qmui_color(withHexString: "#888E93")!
        dataSource.titleSelectedColor = UIColor.qmui_color(withHexString: "#383C3F")!
        dataSource.titleNormalFont = .systemFont(ofSize: 16, weight: .medium)
        
        segmentedView.backgroundColor = UIColor.white
        segmentedView.delegate = self
        segmentedView.isContentScrollViewClickTransitionAnimationEnabled = false
        segmentedView.dataSource = dataSource

        let lineView = JXSegmentedIndicatorLineView()
        lineView.indicatorColor = UIColor.qmui_color(withHexString: "#2ABD9C")!
        lineView.indicatorWidth = 30
        segmentedView.indicators = [lineView]

        let lineWidth = 1/UIScreen.main.scale
        let bottomLineView = UIView()
//        bottomLineView.backgroundColor = UIColor.lightGray
        bottomLineView.backgroundColor = UIColor(red: 0.90, green: 0.91, blue: 0.95, alpha: 1.00)
        bottomLineView.frame = CGRect(x: 0, y: segmentedView.bounds.height - lineWidth, width: segmentedView.bounds.width, height: lineWidth)
        bottomLineView.autoresizingMask = .flexibleWidth
        segmentedView.addSubview(bottomLineView)

        pagingView.mainTableView.gestureDelegate = self
        pagingView.mainTableView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(headerRefreshAction))
        self.view.addSubview(pagingView)
        
        segmentedView.listContainer = pagingView.listContainerView

        //扣边返回处理，下面的代码要加上
        pagingView.listContainerView.scrollView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
        pagingView.mainTableView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
        headerRefreshAction()
        
        if (XS_Singleton.shared.infoModel?.userBO.userTypeEnum() ?? XS_UserType.user) == XS_UserType.vip {
            pagingView.reloadData()
        }
    }
    
    @objc func headerRefreshAction(){
        //下拉刷新
        requestData()
        for subVC in vcArray {
            subVC.headerRefesh()
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        pagingView.frame = self.view.bounds
    }

    func preferredTableHeaderView() -> XS_LearnHeaderView {
        let headerView = XS_LearnHeaderView.init(frame: CGRect.init(x: 0, y: 0, width: .screenWidth, height: 465))
        headerView.delegate = self
        return headerView
    }

    func preferredPagingView() -> JXPagingView {
        return JXPagingView(delegate: self)
    }
    
    func requestData(){
        //        /plan/queryUserLearnTimeInThisWeek
        XS_NetWork.requestJson("/plan/queryUserLearnTimeInThisWeek")
            .mapModel(type: XS_LearnTimeModel.self) // 返回 模型对象 和原始数据
            .subscribe(onNext: { model, resp in
                self.userHeaderView.model = model
                self.pagingView.mainTableView.mj_header?.endRefreshing()
            })
    }
}

extension BaseViewController : XS_LearnHeaderViewDelegate{
    func learnHeaderView(learnHeaderView: XS_LearnHeaderView, didClickVipView: UIView) {
        let vipVC = XS_VIPVC()
        navigationController?.pushViewController(vipVC, animated: true)
    }
}

extension BaseViewController: JXPagingViewDelegate {

    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
        return tableHeaderViewHeight + 8
    }

    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        return userHeaderView
    }

    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return headerInSectionHeight
    }

    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return segmentedView
    }

    func numberOfLists(in pagingView: JXPagingView) -> Int {
        return titles.count
    }

    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        return vcArray[index]
    }
}

extension BaseViewController: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = (index == 0)
    }
}

extension BaseViewController: JXPagingMainTableViewGestureDelegate {
    func mainTableViewGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        //禁止segmentedView左右滑动的时候，上下和左右都可以滚动
        if otherGestureRecognizer == segmentedView.collectionView.panGestureRecognizer {
            return false
        }
        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
    }
}
